﻿using IBLL;
using IDAL;
using Microsoft.Extensions.Logging;
using Model;

namespace BLL
{
    public class UserBLL : IUserBLL
    {
        public UserBLL(IBaseDAL<FoodModel> dal1,IBaseDAL<HelpModel> dal,IBaseDAL<FoodTypeModel> dal2,ILogger<UserBLL> logger)
        {
            Dal1 = dal1;
            Dal = dal;
            Dal2 = dal2;
            Logger = logger;
        }

        public IBaseDAL<FoodModel> Dal1 { get; }
        public IBaseDAL<HelpModel> Dal { get; }
        public IBaseDAL<FoodTypeModel> Dal2 { get; }
        public ILogger<UserBLL> Logger { get; }

        public async Task<int> AddFood(FoodModel models)
        {
            return await Dal1.AddAsync(models);
        }

        public async Task<int> AddHelp(HelpModel model)
        {
            model.HelpId = DateTime.Now.ToString("yyyyMMddHHm");
            return await Dal.AddAsync(model);
        }

        public dynamic GetAllFood(string? Name, int? FoodId)
        {
            var q = Dal1.QueryAsync();
            if (!string.IsNullOrEmpty(Name))
            {
                q = q.Where(x=>x.Name.Contains(Name));
            }
            if (FoodId > 0)
            {
                q = q.Where(x=>x.FoodId == FoodId);
            }
            var w = Dal2.QueryAsync();
            var query = from x in q
                        join y in w on x.FoodId equals y.FoodId
                        select new
                        {
                            x.Id,
                            x.FoodId,
                            x.Name,
                            x.img,
                            y.FoodName
                        };
            return query;
        }

        public dynamic GetAllHelp(int PageIndex, int PageSize, string? Name)
        {
            var q = Dal.QueryAsync();
            if (!string.IsNullOrEmpty(Name))
            {
                q = q.Where(x=>x.Name.Contains(Name));
            }
            return new
            {
                count = q.Count(),
                data = q.OrderBy(x=>x.Id).Skip((PageIndex-1)* PageSize).Take(PageSize).ToList(),
            };
        }

        public List<HelpModel> GetAlls()
        {
            return Dal.QueryAsync().ToList();
        }

        public List<FoodTypeModel> GetAllType()
        {
            return Dal2.QueryAsync().ToList();
        }

        public Task<int> UpdDel(int id, bool isDel)
        {
            var s = Dal.QueryAsync().FirstOrDefault(x => x.Id == id);
            s.isDel = !isDel;
            return Dal.UpdateAsync(s);
        }

        public async Task<int> UpdState(string idlist)
        {
            List<int> list = idlist.Split(',').Select(x=>Convert.ToInt32(x)).ToList();
            var data = Dal.QueryAsync().Where(x=>list.Contains(x.Id)).ToList();
            foreach (var item in data)
            {
                item.State = !item.State;
            }
            return await Dal.UpdateRangeAsync(data);
        }
    }
}
